package tr.edu.metu.is550.isell.rest.jersey.context;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
@Produces(value = MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
    private final static String PACKAGE = "tr.edu.metu.is550.isell.";

    private ObjectMapper objectMapper;

    public JacksonContextResolver() throws Exception {
        AnnotationIntrospector pair = new AnnotationIntrospector.Pair(new JaxbAnnotationIntrospector(), new JacksonAnnotationIntrospector());

        this.objectMapper = new ObjectMapper()
                .configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)
                .configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true)
                .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .setAnnotationIntrospector(pair);
    }

    @Override
    public ObjectMapper getContext(Class<?> aClass) {
        Package aPackage = aClass.getPackage();
        if (aPackage == null)
            return null;

        String packageName = aPackage.getName();

        if (StringUtils.isEmpty(packageName))
            return null;

        if (aPackage.getName().contains(PACKAGE))
            return objectMapper;

        return null;
    }
}
